package com.example.bootdemo.common.exception;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;


/**
 * @author 公众号:干货食堂
 * @date 2021/10/2 13:40
 * @description: 处理404请求  返回自定义json信息
 */
@RestController
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class NotFound404Exception implements ErrorController {

    @RequestMapping
    public void error(HttpServletRequest request, NoHandlerFoundException exception) throws Exception {
        HttpStatus status = this.getStatus(request);
        if (HttpStatus.NOT_FOUND.equals(status)) {
            throw  exception;
        }
        throw new RuntimeException();
    }

    /**
     * 得到状态码
     * @param request
     * @return
     */
    public HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        } else {
            try {
                return HttpStatus.valueOf(statusCode);
            } catch (Exception var4) {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }
        }
    }

    @Override
    public String getErrorPath() {
        return null;
    }
}
